<?php

include 'AlunoController.php';

class TurmaController extends Controller {

	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout = '//layouts/column2';
	public $alunos = array();

	/**
	 * @return array action filters
	 */
	public function filters() {
		return array(
				'accessControl', // perform access control for CRUD operations
				'postOnly + delete', // we only allow deletion via POST request
		);
	}

	public function actionCadastrados($id) {

		if (isset($_POST['arv'])) {
			$testvar = $_POST['arv'];

			$this->removeTurmaLigacoes($id);
			$nomes = $this->getNamesFromString($testvar);
			$this->insertAlunosNaTurma($id, $nomes);
			$this->redirect(array('view', 'id' => $id));
		}


		$this->render('cadastrados', array(
				'model' => TurmaController::loadModel($id),));

	}

	/** Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionPlano($id)
	{
		$model = $this->loadModel($id);
		$plano = new PlanoTurma('search');

		if(isset($_POST['PlanoTurma'])) {
			$newPlano = new PlanoTurma();
			$newPlano->attributes = $_POST['PlanoTurma'];
			$newPlano->turma_id = $id;

			if($newPlano->validate()) {
				$newPlano->save();
			}
			
			$this->redirect(array('plano','id'=>$id));
		}

		$this->render('plano',array(
				'model'=> $model,
				'plano'=>$plano,

		));
	}

	public function insertAlunosNaTurma($id, $alunos) {
		foreach ($alunos as $aluno) {
			$turmaAluno = new TurmaHasAluno;
			$turmaAluno->turma_int = $id;
			$turmaAluno->aluno_id = $aluno->id;
			$turmaAluno->save();
			$aluno->status = 'Ativo';
			$aluno->save();
		}
	}

	public function getNamesFromString($string) {
		$rows = explode(',', $string);
		$alunos = array();

		foreach ($rows as $row) {
			$aluno = Aluno::model()->findByAttributes(array('id' => $row));
			if ($aluno != null) {
				$alunos[] = $aluno;
			}
		}

		return $alunos;
	}

	public function removeTurmaLigacoes($id) {
		$model = TurmaController::loadModel($id);
		$turmas = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $id));
		foreach ($turmas as $turma) {
			if($model->classe->unica == 1) {
				$aluno = Aluno::model()->findByPk($turma->aluno_id);
				$aluno->status = "Em Espera";
			}
			$turma->delete();
		}
	}

	public function getAlunosMatriculados($turma) {
		$alunosNaTurma = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $turma->id));
		$alunos = array();
		foreach ($alunosNaTurma as $ant) {
			$alunos[] = Aluno::model()->findByAttributes(array('id'=>$ant->aluno_id));
		}
		return $alunos;
	}

	public function getDisponiveisAlunos($turma) {
		$alunos = Aluno::model()->findAllByAttributes(array('polo_id'=>Yii::app()->session['polo_id']));
		$turmas = Turma::model()->findAllByAttributes(array('unica' => $turma->unica, 'ano' => $turma->ano,'polo_id'=>Yii::app()->session['polo_id']));
		$alunosReais = array();
		$alunosFinais = array();
		foreach ($turmas as $turma) {
			$alunosNaTurma = TurmaHasAluno::model()->findAllByAttributes(array('turma_int' => $turma->id));
			foreach ($alunosNaTurma as $alunoNaTurma) {
				$alunosReais[] = Aluno::model()->findByAttributes(array('id' => $alunoNaTurma->aluno_id));
			}
		}

		foreach ($alunos as $aluno) {
			$pertence = false;
			foreach ($alunosReais as $alunoReal) {
				if ($aluno->id == $alunoReal->id) {
					$pertence = true;
					break;
				}
			}
			if ($pertence == false) {
				$alunosFinais[] = $aluno;
			}
		}
		return $alunosFinais;
	}

	public static function criarRecomendacoes($id) {

	}


	public function actions() {
		return array(
				'cadastrados' => array(
						'class' => 'CViewAction',
						'defaultView' => 'cadastrados',
				),
				'plano' => array(
						'class' => 'CViewAction',
						'defaultView' => 'plano',
				),
				'selecionados' => array(
						'class' => 'CViewAction',
						'defaultView' => 'selecionados',
				),
				'imprimir' => array(
						'class' => 'CViewAction',
						'defaultView' => 'imprimir',
				)
		);
	}

	public function actionImprimir($id) {
		$turma = TurmaController::loadModel($id);
		$this->createAndPrintDocument($turma);

	}

	public function findAlunosRecomendados($model) {

		$caracteristicasComClasse = ClasseHasCaracteristica::model()->findAllByAttributes(array('classe_id' => $model->classe_id));
		$caracteristicas = array();
		$alunos = array();
		$position = 0;

		foreach ($caracteristicasComClasse as $caracteristicaClasse) {
			$caracteristicas[$position] = $caracteristicaClasse->caracteristica_id;
			$position++;
		}

		foreach ($caracteristicas as $caract) {
			$alunosComCaracteristica = CaracteristicaAluno::model()->findAllByAttributes(array('caracteristica_id' => caract));
			foreach ($alunosComCaracteristica as $aCC) {
				$aux = Aluno::model()->findByAttributes(array('id' => $aCC->aluno_id));
				if (!array_key_exists($aux->id, $alunos)) {
					$alunos[$aux->id] = 0;
				} else {
					$alunos[$aux->id] = $alunos[$aux->id] + 1;
				}
			}
		}

		return $alunos;
	}
	
	private function createAndPrintDocument($turma) {
		$ESPACO = "                      ";
		$pdf=new PDF_MC_Table();
		$pdf->Open();
		$pdf->AddPage();
		$pdf->Image('.//css/logo_ufam.jpg',10,7,-150);
		$pdf->Image('.//css/feff.png',182,5,-212);
		$pdf->SetFont('Arial','B',12);
		$pdf->Cell(0,5,'UNIVERSIDADE FEDERAL DO AMAZONAS ',0,1, 'C');
		$pdf->Cell(0,5,utf8_decode('FACULDADE DE EDUCAÇÃO FÍSICA E FISIOTERAPIA'),0,1, 'C');
		$pdf->Ln(10);
		$pdf->SetFont('Arial','B',12);
		$pdf->Image('.//css/proamde.png',88,null,-260);
		$pdf->Ln(6);
		$pdf->Cell(0,5,utf8_decode('PLANO DE CURSO'),0,1, 'C');
			
		$pdf->Ln(10);
			
		$faixas_etarias = ClasseHasCaracteristica::model()->findAllByAttributes(array('classe_id'=> $turma->classe_id));
		$faixa_etaria = "";
		foreach($faixas_etarias as $faixa) {
			$etaria = Caracteristica::model()->findByPk(array('id'=>$faixa->caracteristica_id));
			if($etaria->tipo == "Idade") {
				$faixa_etaria = $etaria;
				break;
			}
		}
			
		$pdf->Cell(0,8, utf8_decode('Turma: ' . $turma->nome) ,0,1);
		$pdf->Cell(0,8, utf8_decode("Faixa Etária: " .$faixa_etaria->nome),0,1);
		
		$responsavel = "";
		if($turma->responsavel != null) {
			$responsavel = $turma->responsavel->pessoa->nome;
		}
		
		$pdf->Cell(0,8, utf8_decode("Responsavel: " .$responsavel),0,1);
		$pdf->Ln(5);
		$pdf->SetWidths(array(35, 35, 40, 40, 43));
		
		$pdf->SetFillColor(192,217,217);
		$pdf->SetTextColor(0);
		$pdf->SetDrawColor(0,0,0);
		$pdf->SetLineWidth(.2);
		$pdf->SetFont('','B', 12);
		
		$pdf->Row(array(utf8_decode('Objetivos'), utf8_decode('Conteúdos'), utf8_decode('Procedimentos'), utf8_decode('Recursos'), utf8_decode('Avaliação')));
		$data = $turma->planos;
		
		$dados = Utils::fancyTable($data, $pdf);
		
		$pdf->SetFillColor(224,235,255);
		$pdf->SetTextColor(0);
		$pdf->SetFont('');
		$pdf->SetFont('Arial','',8);
		
		if($dados != null && !empty($dados)) {
			foreach ($dados as $dado) {
				$pdf->Row($dado);
			}
		}
		$pdf->Ln(3);
		$pdf->SetFont('Arial','B',12);
		$pdf->Output('plano_de_curso.pdf');
			
		$path = Yii::app()->request->hostInfo . Yii::app()->request->baseURL . '/plano_de_curso.pdf';


		return Yii::app()->getRequest()->sendFile('plano_de_curso_'.$turma->nome.'.pdf', @file_get_contents($path));
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
				array('allow', // allow all users to perform 'index' and 'view' actions
						'actions' => array('index', 'view', 'cadastrados', 'plano', 'selecionados','imprimir'),
						'users' => array('@'),
				),
				array('allow', // allow authenticated user to perform 'create' and 'update' actions
						'actions' => array('create', 'update'),
						'users' => array('@'),
				),
				array('allow', // allow admin user to perform 'admin' and 'delete' actions
						'actions' => array('admin', 'delete'),
						'users' => array('@'),
				),
				array('deny', // deny all users
						'users' => array('*'),
				),
		);
	}

	public function actionSelecionados($id) {
		$turmas = new Turma('search');
		$funcionario = Funcionario::model()->findByPk($id);
		$dataProvider = $turmas->search_by_funcionario($id);
		
		$this->render('selecionados', array(
				'provider' => $dataProvider,
				'turmas' => $turmas,
		));
	}
	
	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id) {

		$turma = TurmaController::loadModel($id);

		$this->render('view', array(
				'model' => $turma,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate() {

		$model = new Turma;
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Turma'])) {

			$model->attributes = $_POST['Turma'];
			$model->polo_id = Yii::app()->session['polo_id'];
			$model->unica = Classe::model()->findByPk($model->classe_id)->unica;
			if ($model->save()) {
				$this->ligarAlunosATurma($model);
				$this->redirect(array('view', 'id' => $model->id));
			}
		}
			$this->render('create', array(
					'model' => $model,
			));
	}
	public function hasOpenedPeriodo() {
		if (Periodo::semPeriodosAbertos(Yii::app()->session['polo_id'])) {
			return false;
		}
		return true;
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id) {
		$model = TurmaController::loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if (isset($_POST['Turma'])) {
			$model->attributes = $_POST['Turma'];
			if ($model->save()) {
				$this->ligarAlunosATurma($model);
				$this->redirect(array('view', 'id' => $model->id));
			}
		}

		$this->render('update', array(
				'model' => $model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id) {
		$turma = TurmaController::loadModel($id);
		$turma->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if (!isset($_GET['ajax']))
			$this->redirect(array('admin'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex() {
		$this->actionAdmin();

	}

	public function ligarAlunosATurma($model) {
			if(Yii::app()->session['polo_id'] == 1) {
					$nomes = Aluno::model()->findAllByAttributes(array('polo_id'=>Yii::app()->session['polo_id'], 'status'=>'Ativo'));
					if($nomes != null && !empty($nomes) && $model->ano == date('Y')) {
						foreach($nomes as $aluno) {
							$turmaHasAluno = TurmaHasAluno::model()->findByAttributes(array('aluno_id'=>$aluno->id, 'turma_int'=>$model->id));
							if($turmaHasAluno == null) {
								$turmaHasAluno = new TurmaHasAluno;
								$turmaHasAluno->turma_int = $model->id;
								$turmaHasAluno->aluno_id = $aluno->id;
							}
							$turmaHasAluno->status = 'Ativo';
							$turmaHasAluno->save();
							$aluno->status = 'Ativo';
							$aluno->save();
						}
					}

			}
	}
	
	/**
	 * Manages all models.
	 */
	public function actionAdmin() {
		$model = new Turma('search');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Turma']))
			$model->attributes = $_GET['Turma'];

		$this->render('admin', array(
				'model' => $model,
		));
	}

	public function createReturnableUrl($view, $attributes) {
		$this->redirect(array('view', 'id' => $model->id));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return Turma the loaded model
	 * @throws CHttpException
	 */
	public static function loadModel($id) {
		$model = Turma::model()->findByPk($id);
		$model->responsavel = Funcionario::model()->findByAttributes(array('id'=>$model->responsavel_id));
		$model->classe = Classe::model()->findByAttributes(array('id'=>$model->classe_id));
		$model->polo = Polo::model()->findByAttributes(array('id'=>$model->polo_id));
		$model->turmaHasAlunos = TurmaHasAluno::model()->findAllByAttributes(array('turma_int'=>$model->id));
		if($model->turmaHasAlunos != null) {
			foreach($model->turmaHasAlunos as $tuAluno) {
				$tuAluno->frequencias = Frequencia::model()->findAllByAttributes(array('turma_has_aluno_id'=>$tuAluno->id), array('order'=>'aula_id'));
				$tuAluno->aluno = AlunoController::loadModel($tuAluno->aluno_id);
			}
		}
		$model->aulas = Aula::model()->findAllByAttributes(array('turma_id'=> $model->id));
		if ($model === null)
			throw new CHttpException(404, 'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param Turma $model the model to be validated
	 */
	protected function performAjaxValidation($model) {
		if (isset($_POST['ajax']) && $_POST['ajax'] === 'turma-form') {
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

}
